﻿@implements IDisposable
@inject AuthenticationStateProvider AuthenticationStateProvider

<CascadingValue TValue="System.Threading.Tasks.Task<AuthenticationState>" Value="@_currentAuthenticationStateTask" ChildContent="@ChildContent" />

@code {
    private Task<AuthenticationState>? _currentAuthenticationStateTask;

    /// <summary>
    /// The content to which the authentication state should be provided.
    /// </summary>
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    protected override void OnInitialized()
    {
        AuthenticationStateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged;

        _currentAuthenticationStateTask = AuthenticationStateProvider
            .GetAuthenticationStateAsync();
    }

    private void OnAuthenticationStateChanged(Task<AuthenticationState> newAuthStateTask)
    {
        _ = InvokeAsync(() =>
        {
            _currentAuthenticationStateTask = newAuthStateTask;
            StateHasChanged();
        });
    }

    void IDisposable.Dispose()
    {
        AuthenticationStateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged;
    }
}
